<?php
/**
 @prefix : <http://purl.org/net/ns/doas#> .
 @about: "<app/controllers/article_controller.php>", a: ":PHPScript",
 :shortdesc "This is a Article placeholder class.";
 :author [:name "Logue"; :homepage <http://logue.be/> ];
 :license <http://www.gnu.org/licenses/gpl-3.0.html>;
 :dependencies "none".
*/
// Lorelei Article Article placeholder class
// Copyright (c)2008-2009 Logue <http://logue.be/> All rights reserved.

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

class ArticlesController extends AppController {

	var $name = 'Articles';
	var $helpers = array('Html', 'Form', 'Time');
	var $uses = array('Article', 'Category', 'Comment','Mml');

	function beforeFilter(){
		parent::beforeFilter();
		//ログインを必要としない処理 指定しないと全てのactionでログインが必要となるので注意
		$this->Auth->allow('view','index','category','search','rss','recent','json','tag');
		$auth = $this->Auth->user();	// セッション読み込み
	}

/*************************************************************************************************/
// 基本コマンド

	// 一覧
	function index($id = null,$type = null,$limit=20) {

		switch($type){
			// カテゴリ別
			case 'category' :
				if (!$id) {
					$this->Session->setFlash(sprintf(__('Invalid id for %s.', true), __('Category',false)));
					$this->redirect(array('action'=>'index'));
				}
				$cond = array('Article.category_id'=>$id);
				$this->pageTitle = __('Category',true);
			break;

			// ユーザ別
			case 'user' :
				if (!$id) {
					$this->Session->setFlash(sprintf(__('Invalid id for %s.', true), __('User',false)));
					$this->redirect(array('action'=>'index'));
				}
				$cond = array('Article.user_id'=>$id);
				$this->pageTitle = __('User',true);
			break;

			case 'rank' :
				if (!$id) {
					$this->Session->setFlash(sprintf(__('Invalid id for %s.', true), __('Rank',false)));
					$this->redirect(array('action'=>'index'));
				}
				$cond = array('Article.rank_id'=>$id);
				$this->pageTitle = __('Rank',true);
			break;

			// 全部
			default:
				$cond = null;
			break;
		}

		$this->Article->recursive = 0;
		$articles = $this->paginate('Article',$cond);

		if ($articles){
			$this->set('articles', $articles);
			$this->set('id', $id);
			$this->set('type', $type);
		}else{
			$this->cakeError('error404');
		}
	}

	// 表示
	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(sprintf(__('Invalid id for %s.', true), __('Article',true)));
			$this->redirect(array('action'=>'index'));
		}

		// データー取得
		$article = $this->Article->read(null, $id);
		if($article){
			$this->set('article', $article);
			$this->set('instrument', $this->Article->Mml->Instrument->find('list'));
			$this->set('ranks', $this->Article->Mml->Rank->find('list'));

			// 前後ページ
			$this->set('neighbours', $this->Article->find('neighbors',array('field'=>'Article.id', 'value'=>$id)));

			$this->pageTitle = $article['Article']['title'];
		
			// コメント
			$this->set('comments', $this->Comment->findAllByArticle_id($id));
		}else{
			$this->cakeError('error404');
		}
	}

	// 追加
	function add() {
		$this->pageTitle = __('New Article',true);

		if (!$this->Auth->user())
			$this->Session->setFlash(sprintf(__('You have not permission to %1$s this %2$s.', true), __('Submit',true),__('Article',true)));

		if (!empty($this->data)) {
			$this->Article->create();
			$this->Mml->create();
			if ($this->Article->validates()) {

				// XHTMLに変換（fontタグをspanに変更するなど）
			//	$this->data['Article']['body'] = tidy_repair_string($this->data['Article']['body'],array('indent' => true, 'output-xhtml' => true),'utf-8');
			//	$this->data['Article']['body'] = strip_tags($this->data['Article']['body'], '<p><br><pre><span>');
				$this->data['Article']['lyrics'] = strip_tags($this->data['Article']['lyrics']);
				// http://blog.x-ite.jp/archives/79
				if ($this->Article->save($this->data)){
					// MMLを投稿
					$this->data['Mml']['article_id'] = $this->Article->getLastInsertId();	// 保存した記事のIDを取得
					$this->data['Mml']['ch1'] = ereg_replace('[^0-9a-glnortvA-GLNORTV#<>.,&+-]','',$this->data['Mml']['ch1']);
					$this->data['Mml']['ch2'] = ereg_replace('[^0-9a-glnortvA-GLNORTV#<>.,&+-]','',$this->data['Mml']['ch2']);
					$this->data['Mml']['ch3'] = ereg_replace('[^0-9a-glnortvA-GLNORTV#<>.,&+-]','',$this->data['Mml']['ch3']);
					$this->data['Mml']['user_id'] = $this->data['Article']['user_id'];
					// タグの保存
					if ($this->data['Article']['tags']) $this->data['Tag']['name'] = $this->Article->Tag->saveTags($this->data['Article']['tags']);
					
					//pr($this->data);
					if ($this->Mml->save($this->data)){
						$this->Session->setFlash(sprintf(__('The %s has been saved.',true), __('MML Track',true)));
						$this->redirect(array('controller'=>'articles','action'=>'view',$this->data['Mml']['article_id']));
					}else{
						$this->Session->setFlash(sprintf(__('The %s could not be saved. Please, try again.', true), __('MML',true)));
					}
				} else {
					$this->Session->setFlash(sprintf(__('The %s could not be saved. Please, try again.', true), __('Article',true)));
				}
			} else {
				$this->Session->setFlash(__('The wrong value is included.',true));	// データーバリテーション
			}
		}

		// カテゴリ一覧を読み込み
		$this->set('categories',$this->Article->Category->find('list'));
		$this->set('instruments', $this->Article->Mml->Instrument->find('list'));
		$this->set('ranks', $this->Article->Rank->find('list'));
	}

	// 編集
	function edit($id = null) {
		$this->pageTitle = __('Edit Article',true);

		// 存在するか？
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(sprintf(__('Invalid id for %s.', true), __('Article',true)));
			$this->redirect(array('action'=>'index'));
		}

		// ユーザチェック
		$auth = $this->Auth->user();

		// 保存処理
		if (!empty($this->data)) {
			// ユーザチェック
			if ($auth['User']['id'] != $this->data['Article']['user_id']){
				$this->Session->setFlash(sprintf(__('You have not permission to %1$s this %2$s.', true), __('Save',true),__('Article',true)));
				$this->redirect(array('action'=>'view',$id));
			}

			// XHTMLに変換（fontタグをspanに変更するなど）
//			$this->data['Article']['body'] = tidy_repair_string($this->data['Article']['body'],array('indent' => true, 'output-xhtml' => true),'utf-8');

			// タグの保存
			if ($this->data['Article']['tags']) $this->data['Tag']['name'] = $this->Article->Tag->saveTags($this->data['Article']['tags']);

			if ($this->Article->save($this->data)) {
				$this->Session->setFlash(sprintf(__('The %s has been saved.', true), __('Article',true)));
				$this->redirect(array('action'=>'view',$id));
			} else {
				$this->Session->setFlash(sprintf(__('The %s could not be saved. Please, try again.', true),__('Article',true))).pr($this->data);
			}
		}else{
			$this->data = $this->Article->read(null, $id);
			if ($auth['User']['id'] != $this->data['Article']['user_id']){
				$this->Session->setFlash(sprintf(__('You have not permission to %1$s this %2$s.', true), __('Edit',true),__('Article',true)));
				$this->redirect(array('action'=>'view',$id));
			}
			if (count($this->data['Tag'])){
				$tags = null;
				foreach ($this->data['Tag'] as $tag){ $tags .= $tag['name'] . ","; }
				$this->data['Article']['Tags'] = substr($tags, 0, -1);
			}
		}
		$this->set('article',$this->data);

		// カテゴリ一覧を読み込み
		$this->set('categories',$this->Article->Category->find('list'));
		$this->set('ranks', $this->Article->Mml->Rank->find('list'));
	}

	// 削除
	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(sprintf(__('Invalid id for %s.', true), __('Article',true)));
			$this->redirect(array('action'=>'index'));
		}else{
			// ユーザチェック
			$auth = $this->Auth->user();
			$article = $this->Article->read(null, $id);
			if ($auth['User']['id'] != $article['Article']['user_id']){
				$this->Session->setFlash(sprintf(__('You have not permission to %1$s this %2$s.', true), __('Delete',true),__('Article',true)));
				$this->redirect(array('action'=>'view',$id));
			}

			if ($this->Article->del($id)) {
				$this->Session->setFlash(sprintf(__('Your %s has been deleted.', true),__('Article',true)));
				$this->redirect(array('action'=>'index'));
			}
		}
	}

	// MMLトラック追加
	function addMml($id = null) {
		if (!$id) {
			$this->Session->setFlash(sprintf(__('Invalid id for %s.', true), __('Article',true)));
			$this->redirect(array('action'=>'index'));
		}

		$this->redirect(array('controller'=>'mmls','action'=>'add',$id));
	}

/*************************************************************************************************/
// 拡張コマンド

	function tag($id = null) {
		$this->set('id', $id);
		if(!$id) {
			$this->action = 'view';
		} else {
	//		$this->Article->recursive = '1';
			$article = $this->Article->read(null, $id);

			if(!empty($this->data)) {
				$tags = $this->Article->Tag->saveTags($this->data['Article']['tags']);

				if(!empty($article['Tag'])) {
					foreach($article['Tag'] as $var) {
						$tags[] = $var['id'];	// 対応するTagのId
					}
				}

				$tags = array_unique($tags);	// 重複を削除

				foreach ($tags as $tag_id){
					$existing = $this->Article->ArticlesTag->find(array('article_id'=>$id,'tag_id'=>$tag_id));	// 重複チェック
					if (!$existing){
						$this->Article->ArticlesTag->save(array(
							'ArticlesTag'=>array(
								'tag_id'=>$tag_id,
								'article_id'=>$id
							)
						));
					}
				}
				$this->data['Article']['id'] = $id;

				if($this->Article->save($this->data)) {
					$this->set('tags_added', true);
					$this->Article->cacheQueries = false;
					$article = $this->Article->read(null, $id);
				}	
			}
		}
		$this->redirect(array('action'=>'view','id'=>$id));
	}

	// タグの削除処理
	function remove_tag($article_id = null,$id = null){
		if (!$article_id) {
			$this->Session->setFlash(sprintf(__('Invalid id for %s.', true), __('Article',true)));
			$this->redirect(array('action'=>'index'));
		}else{

			// ユーザチェック
			$auth = $this->Auth->user();
			$article = $this->Article->read(null, $article_id);
			// ユーザチェック
			if ($auth['User']['id'] != $article['Article']['user_id']){
				$this->Session->setFlash(sprintf(__('You have not permission to %1$s this %2$s.', true), __('Delete',true),__('Tag',true)));
				$this->redirect(array('action'=>'view',$article_id));
			}

			if ($this->Article->ArticlesTag->del($id)) {
				$this->Session->setFlash(sprintf(__('Your %s has been deleted.', true),__('Tag',true)));
				$this->redirect(array('action'=>'view',$article_id));
			}
		}
	}

	// コメント追加
	function commentadd() {
		if (!empty($this->data)) {
			if ($this->Comment->save($this->data)) {
				$this->Session->setFlash(sprintf(__('The %s has been saved.', true), __('Comment',true)));
				$this->redirect(array('action'=>'view','id'=>$this->data['Comment']['article_id']));
			} else {
				$this->Session->setFlash(sprintf(__('The %s could not be saved. Please, try again.', true), __('Comment',true)));
			}
		}
	}

	// 検索
	function search() {
		$this->pageTitle = __('Search',true);
		if(!empty($this->data)) {
			uses('sanitize');
			$sanitize = new Sanitize();
			$words = $sanitize->paranoid($this->data['Search']['words'], array(' '));

			switch($this->data['Search']['type']){
				case 'tags':
					$conditions = array('Tag.name' => 'LIKE %'.$words.'%');
					$tags = $this->Article->Tag->search($conditions);

					$ids = array();
					foreach($tags as $tag) {
						$ids['Article.id'][] = $tag['Article']['id'];
					}

					if (!empty($ids)) {
						$articles = $this->Article->find('all',$ids);
					} else {
						$articles = array();
					}
				break;
				default:
					$conditions = array('Article.body' => 'LIKE %' . $words . '%');
					$this->Article->recursive = 0;
					$articles  = $this->Article->find('all', array('condition'=>$conditions));
				break;
			}

			

			$this->set(compact('articles', 'words'));
		} else {
			$this->set('words', null);
		}
	}

/*************************************************************************************************/

	function rss($type = null,$id = null,$limit=15) {
		$this->layout = 'ajax';
		
		switch($type){
			// カテゴリ別
			case 'category' :
				if (!$id) {
					$this->Session->setFlash(sprintf(__('Invalid id for %s.', true), __('Category',false)));
					$this->redirect(array('action'=>'index'));
				}
				$cond = array('Article.category_id'=>$id);
			break;

			// ユーザ別
			case 'user' :
				if (!$id) {
					$this->Session->setFlash(sprintf(__('Invalid id for %s.', true), __('User',false)));
					$this->redirect(array('action'=>'index'));
				}
				$cond = array('Article.user_id'=>$id);
			break;

			// ランク別
			case 'rank' :
				if (!$id) {
					$this->Session->setFlash(sprintf(__('Invalid id for %s.', true), __('User',false)));
					$this->redirect(array('action'=>'index'));
				}
				$cond = array('Article.rank_id'=>$id);
			break;

			// 全部
			default:
				$cond = null;
			break;
		}
		$this->set('articles', $this->Article->find('all',array(
			'conditions' => $cond,
			'order' => array('Article.created DESC'),
			'limit' => $limit)
		));
	}

/*************************************************************************************************/

	function recent($limit = 10) {
		// 最新記事呼び出し
		if($this->params['requested'] === 1){
			$this->Article->recursive = -1;
			return $this->Article->find('all', array(
				'order' => array('Article.created DESC'),
				'limit' => $limit)
			);
		} else {
			// elementsからの呼び出し専用なので普通にアクセスした場合はトップページにリダイレクト。
			$this->redirect('/');
		}
	}

	function incremental_search_source($word=null) {
		if($this->params['requested'] === 1){
			if ($word == null) $word=$this->data['Article']['source'];
			$conditions = array('Article.source' => 'LIKE %'.$word.'%');
			$this->set('source_list',$this->Article->findAll($conditions));
		} else {
			// 内部呼び出し専用なので普通にアクセスした場合はトップページにリダイレクト。
			$this->redirect('/');
		}
	}
}
?>